<?php
namespace app\api\controller;

use app\common\controller\KdApi;
use think\Db;



header('Access-Control-Allow-Origin:*');
header("Access-Control-Allow-Credentials:true");
header("Access-Control-Max-Age:3600");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,SessionToken,Token,ID");
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS');


class Order extends Check
{
    protected function _initialize(){
        parent::_initialize();
    }
    /**
     * 订单列表
     * status
     * 全部all 待发货1 待收货2 已完成3
     */
    public function order_list()
    {
        $status = $this->request->param('status','all');
        $where['user_id'] = $this->uid;
        if($status!='all'){
            $where['status'] = $status;
        }
        $r=Db::name('order')->where($where)->order('id desc')->field('id,order_number,good_name,good_image,attribute,number,status,pay_money,add_time')->select();
        if($r){
            foreach ($r as $k=>$v) {
                $r[$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
                $r[$k]['good_image'] = 'http://' . $_SERVER['SERVER_NAME'].'/public'.$v['good_image'];
            }
            return $this->api->splash(1,'获取成功',$r);
        }else{
            return $this->api->splash(0,'没有数据');
        }
    }
    /*
     * 订单详情
     *
     * 状态
     * 收货的信息
     * 商品信息
     * 价格的信息
     * 快递单号信息
     * 订单号
     * 创建时间
     * 支付时间
     * 发货时间
     * */
    public function order_info()
    {
        if($this->request->isPost()){
            $order_id = $this->request->param('id');
            if(!isset($order_id)||empty($order_id)){
                return $this->api->splash(0,'未获取到订单id');
            }
            $r = Db::name('order')->where('id',$order_id)->field('id,status,address,contacts,mobile,remarks,good_name,good_image,price,attribute,number,pay_type,freight,pay_money,pay_time,add_time,pay_status')->find();
            if($r){
                if($r['status']!=0) {
                    $r['express_time'] = Db::name('express')->where('order_id', $r['id'])->value('add_time');
                    $r['express_number'] = Db::name('express')->where('order_id', $r['id'])->value('express_number');
                    $r['express_time'] = date('Y-m-d H:i:s', $r['express_time']);
                }
                $r['good_image'] = 'http://' . $_SERVER['SERVER_NAME'].'/public'.$r['good_image'];
                $r['add_time'] = date('Y-m-d H:i:s',$r['add_time']);
                $r['pay_time'] = date('Y-m-d H:i:s',$r['pay_time']);
                return $this->api->splash(1,'获取成功',$r);
            }else{
                return $this->api->splash(0,'没有数据');
            }
        }else{
            return $this->api->splash(0,'请求错误');
        }
    }
    /*
     * 订单生成
     *
     * 支付状态
     * 收货信息
     * 商品信息（数量）
     * 支付金额
     * 支付类型
     *
     * */
    public function order_save()
    {
        if($this->request->isPost()){
            $data = $this->request->param();
            if(!isset($data['good_id'])||!isset($data['number'])||empty($this->uid)||!isset($data['remarks'])||!isset($data['mobile'])||!isset($data['contacts'])||!isset($data['address'])||!isset($data['pay_type'])){
                return $this->api->splash(0,'订单信息不完整');
            }
            $good = Db::name('good')->where('id',$data['good_id'])->find();
            if($good['freight_type']==1){
                $freight = $good['freight'] * $data['number'];
            }else{
                $freight = $good['freight'];
            }
            $order_money = $freight + $good['price'] * $data['number'];
            $save = [
                'order_number' => date('YmdHis').rand(1000,9999),
                'order_money' => $order_money,
                'good_id' => $data['good_id'],
                'good_name' => $good['name'],
                'good_image' => $good['image'],
                'price' => $good['price'],
                'attribute' => $good['attribute'],
                'number' => $data['number'],
                'user_id' => $this->uid,
                'status' => 0,
                'remarks' => $data['remarks'],
                'mobile' => $data['mobile'],
                'contacts' => $data['contacts'],
                'address' => $data['address'],
                'add_time' => time(),
                'pay_type' => $data['pay_type'],
                'freight' => $freight,
            ];
            $r = Db::name('order')->insertGetId($save);
            if($r){
                return $this->api->splash(1,'订单生成成功');
            }else{
                return $this->api->splash(0,'生成错误');
            }
        }else{
            return $this->api->splash(0,'请求错误');
        }
    }
    /*
     * 根据订单id 实时查询物流状态
     * */
    public function express_info()
    {
        if($this->request->isPost()){
            $order_id = $this->request->param('id');
            if(!isset($order_id)||empty($order_id)){
                return $this->api->splash(0,'未获取到订单id');
            }
            $kd = new  KdApi();
            $order_number = Db::name('order')->where('id',$order_id)->value('order_number');
            $express = Db::name('express')->alias('a')->join('express_class b','a.express_id=b.id')->where('a.order_id',$order_id)->field('a.*,b.name,b.code')->find();
            $r = json_decode($kd->orderSearch($express['express_number'],$express['code'],$order_number),true);
            if($r){
                return $this->api->splash(1,'获取成功',$r);
            }else{
                return $this->api->splash(0,'没有数据');
            }
        }else{
            return $this->api->splash(0,'请求错误');
        }
    }
    /*
     * 点击完成
     * */
    public function express_over()
    {
        if($this->request->isPost()){
            $order_id = $this->request->param('id');
            if(!isset($order_id)||empty($order_id)){
                return $this->api->splash(0,'未获取到订单id');
            }
            $o = Db::name('order')->where('id',$order_id)->update(['status'=>3]);
            $e = Db::name('express')->where('order_id',$order_id)->update(['express_status'=>1,'express_time'=>time()]);
            if($o&&$e){
                return $this->api->splash(1,'订单完成');
            }else{
                return $this->api->splash(0,'出错了，请联系管理员修改订单状态');
            }
        }else{
            return $this->api->splash(0,'请求错误');
        }
    }
    /*
     * 物流回调接口
     * */
    public function express_back()
    {
        $data = $this->request->param('RequestData');
        $eybInfo = json_decode($data,true);
        foreach($eybInfo['Data'] as $index  => $item){
            $info = [
                "LogisticCode" => $item['LogisticCode'],
                "ShipperCode" => $item['ShipperCode'],
                "State" => $item['State'],
                "StateEx" => isset($item['StateEx'])?$item['StateEx']:0,
                "Reason" => isset($item['Reason'])?$item['Reason']:"",
            ];
            if(in_array($info['StateEx'],[3,301,302,304,311])){
                $order_id =   Db::name("order_logistics")->where("",$info["LogisticCode"])->value("order_id");
                \think\Queue::later(config('queue_delaytime')['order']['status3'],'\app\api\queue\OrderStatus', ['status' => 3, 'order_id' => $order_id]);
                $count = count($item['Traces']);
                @$fineTime = $item['Traces'][$count]["AcceptTime"];
                @Db::name("order")->where("id",$order_id)->update(['arrival_time'=>strtotime($fineTime)]);
            }
            $expressInfo = $this->infoModel->get(['LogisticCode'=>$item['LogisticCode']]);
            if($expressInfo)
                $expressInfo->allowField(true)->save($info,$expressInfo?['id'=>$expressInfo['id']]:null);
            else
                $expressInfo = $this->infoModel->create($info);
            $this->detailModel->where('express_info_id',$expressInfo['id'])->delete();
            $traces = [];
            foreach ($item['Traces'] as $trace){
                $traces[] = [
                    'express_info_id' => $expressInfo['id'],
                    "AcceptTime" => strtotime($trace['AcceptTime']),
                    "AcceptStation" => $trace['AcceptStation'],
                    "Location" => isset($trace['Location'])?$trace['Location']:"无",
                    "Action" => isset($trace['Action'])?$trace['Action']:"无",
                    "Remark" => $trace['Remark'],
                ];
            }
            $this->detailModel->insertAll($traces);
        }
        $data = [
            'EBusinessID' => '1653518',
            'UpdateTime'  => date('Y-m-d H:i:s'),
            'Success'     => true,
            'Reason'      =>""
        ];
        return  $data;
    }
}
